package com.kuaifawu.lwnlawyerclient.Fragment;





import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Xml;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Activity.LWNAboutusActivity;
import com.kuaifawu.lwnlawyerclient.Activity.LWNFindMM;
import com.kuaifawu.lwnlawyerclient.Activity.MainActivity;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.LWNJsonToData;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengDialogButtonListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class KWNMySetFragment extends Fragment implements View.OnClickListener {
    @ViewInject(R.id.myset_aboutus)
    private ImageButton myset_aboutus;
    @ViewInject(R.id.myset_loginout)
    private Button myset_loginout;
    @ViewInject(R.id.myset_xiugaimm)
    private ImageButton myset_xiugaimm;
    @ViewInject(R.id.myset_update)
    private ImageButton myset_update;
    @ViewInject(R.id.show_new)
    private ImageView show_new;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_myset, null);
        ViewUtils.inject(this, rootView);
        InitMySetView();
       // getNewVersion();
        checkVersion();
        return rootView;
    }

    public void InitMySetView() {
        myset_aboutus.setOnClickListener(this);
        myset_loginout.setOnClickListener(this);
        myset_xiugaimm.setOnClickListener(this);
        myset_update.setOnClickListener(this);
    }
private boolean isOnclick=false;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.myset_aboutus:
                Intent intent = new Intent();
                intent.setClass(getActivity(), LWNAboutusActivity.class);
                startActivity(intent);
                break;
            case R.id.myset_loginout:
                loginOut();
//                LWNModel_user user = LWNModel_user.getInstance();
//                user.loginOut(getActivity());
//                Intent mIntent = new Intent(getResources().getString(R.string.broadcast_loginOut));
//                getActivity().sendBroadcast(mIntent);

                break;
            case R.id.myset_xiugaimm:
                Intent xiuintent = new Intent();
                xiuintent.setClass(getActivity(), LWNFindMM.class);
                startActivity(xiuintent);

                break;
            case R.id.myset_update://版本更新
                isOnclick=true;
           proDialog = android.app.ProgressDialog.show(getActivity(), "", "获取中");
                //udateVersion();
                checkVersion();
                popDialog();
                break;


        }
    }
private ProgressDialog proDialog=null;
    /**
     * Umeng检测版本号
     */
    private void checkVersion(){
        setDefault();
        UmengUpdateAgent.setUpdateAutoPopup(false);
        UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
            @Override
            public void onUpdateReturned(int i, UpdateResponse updateResponse) {
                if(proDialog!=null&&proDialog.isShowing()){
                    proDialog.dismiss();
                }
                switch (i){
                    case UpdateStatus.Yes: // has update

                        Toast.makeText(getActivity(), "有更新", Toast.LENGTH_SHORT).show();
                  if(isOnclick){
                      show_new.setVisibility(View.GONE);
                      UmengUpdateAgent.showUpdateDialog(getActivity(), updateResponse);

                }else{
                      show_new.setVisibility(View.VISIBLE);
                  }

                        break;
                    case UpdateStatus.No: // has no update

                        if(isOnclick){
                            Toast.makeText(getActivity(), "已经是最新的版本啦！", Toast.LENGTH_SHORT).show();
                        }
                            show_new.setVisibility(View.GONE);

                        break;
                    case UpdateStatus.NoneWifi: // none wifi
                        Toast.makeText(getActivity(), "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
                        break;
                    case UpdateStatus.Timeout: // time out
                        Toast.makeText(getActivity(), "超时", Toast.LENGTH_SHORT).show();
                        break;

                }
            }
        });

        UmengUpdateAgent.update(getActivity());
       // UmengUpdateAgent.forceUpdate(getActivity());



    }

    /**
     * 每次检测版本恢复默认设置
     */
    private void  setDefault(){
        UmengUpdateAgent.setAppkey(null);
        UmengUpdateAgent.setChannel(null);
        UmengUpdateAgent. setUpdateOnlyWifi(true);
        UmengUpdateAgent. setDeltaUpdate(false);//增量
        UmengUpdateAgent.setUpdateAutoPopup(true);//是否自动的弹出更新提示
        UmengUpdateAgent.setRichNotification(true);//通知栏高级样式
        UmengUpdateAgent.setUpdateUIStyle(UpdateStatus.STYLE_DIALOG);//更新提示的样式  对话框或者是通知栏
        UmengUpdateAgent.setUpdateListener(null);
        UmengUpdateAgent.setDialogListener(null);
        UmengUpdateAgent.setDownloadListener(null);

    }


    /**
     * 对更新提示的对话框的监听
     */
     private void popDialog(){
         UmengUpdateAgent.setDialogListener(new UmengDialogButtonListener() {
             @Override
             public void onClick(int i) {
                 switch (i){
                     case UpdateStatus.Update:
                        // UmengUpdateAgent.downloadedFile(getActivity(),);
                         break;
                     case UpdateStatus.Ignore:
                         show_new.setVisibility(View.VISIBLE);
                         break;
                     case UpdateStatus.NotNow:
                         show_new.setVisibility(View.VISIBLE);
                     break;

                 }

             }
         });

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");
        //MobclickAgent.onResume(getActivity());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
        //MobclickAgent.onPause(getActivity());
    }

    private void loginOut(){
        final ProgressDialog proDialog = android.app.ProgressDialog.show(getActivity(), "", "登录中，请稍候...");
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        String string_url = center.getInstance().getLoginOut(getActivity());
        //System.out.println(string_url);
        HttpUtils http = center.getUtils();
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg  = jsonObject.getString("msg");
            switch (Integer.parseInt(string_code)){
                case 10000:
                    LWNModel_user user = LWNModel_user.getInstance();
                    user.loginOut(getActivity());
                    Intent mIntent = new Intent(getResources().getString(R.string.broadcast_loginOut));
                    getActivity().sendBroadcast(mIntent);
                    break;

                     }
                        } catch (Exception e) {
                            e.printStackTrace();
                            proDialog.dismiss();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                        proDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }
}
